﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

using StockPoint.Util;

namespace StockPoint.Admin
{
    public class BasePage : System.Web.UI.Page
    {
        // Database
        protected DBUtil cDBUtil = new DBUtil(System.Configuration.ConfigurationManager.AppSettings["DBStockPoint"]);

        // Page Settings
        private bool bPassedValid = false;
        private bool bEnableLogin = true;
        private bool bEnableAuth = true;
        private int nMenuIdx = 0;

        #region " Properties - Page Setting "

        /// <summary>
        /// 페이지 설정 통과여부.
        /// </summary>
        protected bool PassedValid
        {
            get { return bPassedValid; }
            set { bPassedValid = value; }
        }

        /// <summary>
        /// 로그인 기능사용.
        /// </summary>
        protected bool EnableLogin
        {
            get { return bEnableLogin; }
            set { bEnableLogin = value; }
        }

        /// <summary>
        /// 권한 기능사용.
        /// </summary>
        protected bool EnableAuth
        {
            get { return bEnableAuth; }
            set { bEnableAuth = value; }
        }

        /// <summary>
        /// 메뉴 Index.
        /// </summary>
        protected int MenuIdx
        {
            get { return nMenuIdx; }
            set { nMenuIdx = value; }
        }

        #endregion

        #region " Property - 페이지명, ... "

        /// <summary>
        /// 페이지명 가져오기
        /// </summary>
        protected string _PageName
        {
            get { return Request.Url.AbsolutePath.Split('/')[Request.Url.AbsolutePath.Split('/').Length - 1].Split('.')[0]; }
        }

        #endregion

        #region " Event - OnInit, Page_Load "

        protected override void OnInit(EventArgs e)
        {
            //LoginCheck();

            // Base 초기화
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                    InitPage();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        #endregion

        #region " Overridable Method "

        /// <summary>
        /// 페이지 초기화.
        /// </summary>
        protected virtual void InitPage() { }

        #endregion

        #region " Validation "

        /// <summary>
        /// 페이지 설정 검사.
        /// </summary>
        protected bool ValidPageSetting()
        {
            if (this.EnableLogin == true && ValidLogin() == false)
            {
                ScriptAlertMove("로그인 후 이용가능합니다.", "/Default.aspx");
                return false;
            }

            if (this.EnableAuth == true && ValidAuth() == false)
            {
                ScriptAlertMove("권한이 없습니다.", "/Default.aspx");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 로그인 체크.
        /// </summary>
        private bool ValidLogin()
        {
            //if (Session[SessionList.User] == null || Session[SessionList.User].ToString() == string.Empty)
            //{
            //    return false;
            //}
            //else
            //{
            //    return true;
            //}
            return true;
        }

        /// <summary>
        /// 권한 체크.
        /// </summary>
        private bool ValidAuth()
        {
            return true;
        }

        #endregion

        #region " Error Handling "

        /// <summary>
        /// 모든 Exception의 에러처리.
        /// </summary>
        /// <param name="ex">발생되는 Exception</param>
        public void HandleError(Exception ex)
        {
            Exception baseExeption = ex.GetBaseException();
            string sErrMsg = FilterErrorMessage(baseExeption);

            ScriptAlert(sErrMsg);

            // Event Log 남김
            //if (!EventLog.SourceExists(Constants.EventLogSource))
            //{
            //    EventLog.CreateEventSource(Constants.EventLogSource, Constants.EventLogError);
            //}

            //EventLog Log = new EventLog();
            //Log.Source = Constants.EventLogSource;
            //Log.WriteEntry(sErrMsg, EventLogEntryType.Error);
            //Log.Dispose();
            //Log.Close();
            //Server.ClearError();
        }

        /// <summary>
        /// Exception에서 보여질 메세지만 필터링.
        /// </summary>
        private string FilterErrorMessage(Exception ex)
        {
            string sErrMsg = ex.Message;

            return sErrMsg;
        }

        #endregion

        #region " Scripts "

        private static string GetStrForAlert(string pValue)
        {
            pValue = pValue.Replace("\"", "\\\"");
            pValue = pValue.Replace("\r\n", "\\n");
            return pValue;
        }

        /// <summary>
        /// Script - Alert.
        /// </summary>
        protected void ScriptAlert(string msg)
        {
            ScriptExec("alert(\"" + GetStrForAlert(msg) + "\");");
        }

        /// <summary>
        /// Script - Alert and Move.
        /// </summary>
        protected void ScriptAlertMove(string msg, string location)
        {
            ScriptExec("alert(\"" + GetStrForAlert(msg) + "\");location.href='" + location + "';");
        }

        /// <summary>
        /// Script - Alert and Back.
        /// </summary>
        protected void ScriptAlertBack(string msg, string location)
        {
            ScriptExec("alert(\"" + GetStrForAlert(msg) + "\");history.back();");
        }

        /// <summary>
        /// Script - Move.
        /// </summary>
        protected void ScriptMove(string location)
        {
            ScriptExec("location.href='" + location + "';");
        }

        /// <summary>
        /// Script - Execute.
        /// </summary>
        protected void ScriptExec(string script)
        {
            if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "RunScript", script, true);
            else
                this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "RunScript", script, true);
        }


        #endregion
    }
}